<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #box {
            width: 100px;
            height: 100px;
            background-color: red;
            position: absolute;
            left: 0px;
            top: 50px;

        }
    </style>
</head>

<body>
    <button>移动</button>
    <div id="box"></div>

    <script>
        let btn = document.getElementsByTagName("button")[0];
        let box = document.getElementById("box");

        let stop;
        // let i = box.offsetTop;
        // let j = box.offsetLeft;
        let flagTop = true;
        let flagleft = true;
        btn.onclick = function () {
            if (btn.innerText == "移动") {
                btn.innerText = "暂停";
                // 移动box盒子，通过改变left和top的值
                stop = setInterval(function () {
                    // 垂直方向
                    if (flagTop) {
                        box.style.top = (++box.offsetTop) + "px";
                        // 判断盒子是否到达可视窗口的最下边
                        // box.offsetHeight:表示元素高度
                        if (parseInt(box.style.top) + box.offsetHeight >= innerHeight) {
                            flagTop = false;
                        }
                    } else {
                        box.style.top = (--box.offsetTop) + "px";
                        if (parseInt(box.style.top) <= 0) {
                            flagTop = true;
                        }
                    }

                    // 水平方向
                    if (flagleft) {
                        box.style.left = (++box.offsetLeft) + "px";
                        // 判断盒子是否到达可视窗口的最下边
                        // box.offsetWidth:表示元素宽度
                        if (parseInt(box.style.left) + box.offsetWidth >= innerWidth) {
                            flagleft = false;
                        }
                    } else {
                        box.style.left = (--box.offsetLeft) + "px";
                        if (parseInt(box.style.left) <= 0) {
                            flagleft = true;
                        }
                    }




                }, 10);

            } else {
                btn.innerText = "移动";
                clearInterval(stop);

            }
        }
    </script>
</body>

</html>